package cn.tedu.ivos.base.security;

import cn.tedu.ivos.user.mapper.UserMapper;
import cn.tedu.ivos.user.pojo.vo.UserVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.HashSet;
import java.util.Set;

@Service
@Slf4j
public class CustomUserDetailsService implements UserDetailsService {
    @Autowired
    UserMapper userMapper;
    @Override
    public UserDetails loadUserByUsername(String username)
            throws UsernameNotFoundException {
        if (username==null){
            throw new UsernameNotFoundException("用户名不能为null");
        }
        UserVO userVO=userMapper.selectByUsername(username);
        if (userVO == null){
            throw new UsernameNotFoundException("用户名或密码错误");
        }
        // 创建自定义的UserDetails对象，并设置用户信息
        CustomUserDetails userDetails = new CustomUserDetails();
        userDetails.setUserId(userVO.getId());
        userDetails.setUsername(userVO.getUsername());
        userDetails.setPassword(userVO.getPassword());
        // 初始化用户权限集合
        Set<GrantedAuthority> authoritySet = new HashSet<>();
        GrantedAuthority authority = new SimpleGrantedAuthority("example");
        authoritySet.add(authority);
        // 设置用户的权限集合
        userDetails.setAuthorities(authoritySet);
        return userDetails;
    }
}
